package cn.wikiflyer.jft.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import cn.wikiflyer.beikang.R;

/**
 * 将raw中得到的数据库文件写入到data数据库中
 * @author chen
 *
 */
public class DBManager {

	private final int BUFFER_SIZE=400000;
	private static final String PACKAGE_NAME="cn.wikiflyer.beikang";
	public static final String DB_NAME="region_2.db";
	public static final String DB_PATH="/data"+Environment.getDataDirectory().getAbsolutePath()+"/"+PACKAGE_NAME;
	private Context mContext;
	private SQLiteDatabase database;
	
	public DBManager(Context context){
		this.mContext=context;
	}
	
	public void openDataBase(){
		this.database=this.openDataBase(DB_PATH+"/"+DB_NAME);
	}
	
	//打开数据库
	private SQLiteDatabase openDataBase(String dbFile){
		File file = new File(dbFile);
		if(!file.exists()){
			//打开raw中到底数据库文件，获得stream流
			InputStream stream = this.mContext.getResources().openRawResource(R.raw.region);
			try {
				
				//将获取的stream流写入到data中
				FileOutputStream outputStream = new FileOutputStream(file);
				byte[] buffer = new byte[BUFFER_SIZE];
				int count=0;
				while((count = stream.read(buffer))>0){
					outputStream.write(buffer, 0, count);
				}
				outputStream.close();
				stream.close();
				SQLiteDatabase db= SQLiteDatabase.openOrCreateDatabase(dbFile, null);
				return db;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return database;
	}
	public void closeDatabase(){
		if(database !=null && database.isOpen()){
			this.database.close();
		}
	}
	
	
}
